package com.beta.restapi.controller;


import com.beta.common.web.ContentType;
import com.beta.dto.cart.CartItemDto;
import com.beta.restapi.internal.Consts;
import com.beta.restapi.internal.auth.AuthService;
import com.beta.restapi.request.cart.CartRequest;
import com.beta.vo.CartItemQuantityVO;
import com.beta.vo.cart.CartItemVO;
import com.beta.restapi.response.wrapper.CartItemRequestWrapper;
import com.beta.restapi.response.wrapper.CartItemVoWrapper;
import com.beta.service.ICartItemsService;
import io.swagger.annotations.Api;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by lichao on 2016/11/17.
 */
@Api(tags = Consts.Resource.CARTITERMS)
@RestController
@RequestMapping(Consts.API_PATH_PREFIX + Consts.Resource.CARTITERMS)
public class CartItemController extends BaseController {

    @Autowired
    private MapperFacade beanMapper;
    @Autowired
    private AuthService authService;
    @Autowired
    private ICartItemsService cartItemsService;

    @GetMapping(value = "", produces = {ContentType.JSON})
    public Object getCartItems(@RequestHeader(Consts.HEADER_AUTH_KEY) String token) {
        List<CartItemDto> cartItemDtos = cartItemsService.getCartItems(getCurrentUserId());
        List<CartItemVO> cartItemVOs = beanMapper.mapAsList(cartItemDtos, CartItemVO.class);
        CartItemVoWrapper cartItemVoWrapper = new CartItemVoWrapper();
        cartItemVoWrapper.setCartItems(cartItemVOs);
        return ok(cartItemVoWrapper);
    }

    @PostMapping(value = "", produces = {ContentType.JSON})
    public Object addCartItem(@RequestHeader(Consts.HEADER_AUTH_KEY) String token,
                              @RequestBody CartRequest cartRequest) {
        return ok(cartItemsService.addCartItem(cartRequest.getProductItemId(), getCurrentUserId()));
    }

    @DeleteMapping(value = "/{cartItemID}", produces = {ContentType.JSON})
    public Object deleteCartItem(@RequestHeader(Consts.HEADER_AUTH_KEY) String token,
                                 @PathVariable("cartItemID") Integer cartItemID) {
        CartItemQuantityVO cartQuantity = new CartItemQuantityVO();
        Integer quantity = cartItemsService.deleteCartItem(cartItemID, getCurrentUserId());
        cartQuantity.setQuantity(quantity);
        return ok(cartQuantity);
    }

    @PatchMapping(value = "/{cartItemId}", produces = {ContentType.JSON})
    public Object updateCartItemQuantity(@RequestHeader(Consts.HEADER_AUTH_KEY) String token,
                                         @PathVariable("cartItemId") Integer cartItemId,
                                         @RequestBody CartItemRequestWrapper cartItemRequestWrapper) {
        Integer quantity = cartItemRequestWrapper.getCartItem().getQuantity();
        return ok(cartItemsService.updateCartItem(cartItemId, quantity, getCurrentUserId()));
    }

}
